/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.common.utils.exception.handle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.ws.rs.core.Response;

import org.apache.cxf.jaxrs.client.ResponseExceptionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.common.utils.exception.InterSystemExceptionSpec;
import com.foreveross.bsl.common.utils.exception.RemoteInvokeException;
import com.foreveross.bsl.common.utils.mapper.JsonMapper;


/**
 * xxx
 * 
 * @author Wangyi
 * @version v1.0
 * 
 * @date 2013-7-30
 * 
 * @author ning 2013-8-23
 * 
 */
public class CxfClientExceptionMapper implements ResponseExceptionMapper<Throwable> {

	private static Logger logger = LoggerFactory.getLogger(CxfClientExceptionMapper.class);
	
	private JsonMapper jsonMapper = JsonMapper.nonEmptyMapper();

	@Override
	public Throwable fromResponse(Response r) {
		InputStream is = (InputStream) r.getEntity();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuilder message = new StringBuilder();
		String line = null;
		try {
			while ((line = br.readLine()) != null) {
				message.append(line);
			}
			
			InterSystemExceptionSpec spec=this.jsonMapper.fromJson(message.toString(), InterSystemExceptionSpec.class);
			return new RemoteInvokeException(spec);
			
		} catch (Exception e){
			logger.error(e.getMessage());
			return e;
		}
		finally{
			try {
				if(is!=null) 
					is.close();
			} catch (IOException e) {
			}
		}
	}

}
